﻿using BW.Demo.Domain.Entities;
using BW.Demo.ErrorCode;
using BW.Demo.Infrastructure.Interfcaes;
using BW.Demo.WebApi.Applications.Commands;
using BW.Demo.WebApi.Dtos;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace BW.Demo.WebApi.Applications.CommandHandlers
{
    public class LoginQueryCommandHandler : IRequestHandler<LoginQueryCommand, APIResult<LoginDTO>>
    {
        /// <summary>
        /// 用户表
        /// </summary>
        private readonly IBaseRespitory<User> userRep;
        /// <summary>
        /// 角色表
        /// </summary>
        private readonly IBaseRespitory<Role> roleRep;
        /// <summary>
        /// 用户角色表
        /// </summary>
        private readonly IBaseRespitory<UserRole> userroleRep;
        private readonly IConfiguration _configuration;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="userRep">用户表</param>
        /// <param name="roleRep">角色表</param>
        /// <param name="userroleRep">用户角色表</param>
        public LoginQueryCommandHandler(IBaseRespitory<User> userRep, IBaseRespitory<Role> roleRep, IBaseRespitory<UserRole> userroleRep,IConfiguration configuration)
        {
            this.userRep = userRep;
            this.roleRep = roleRep;
            this.userroleRep = userroleRep;
            _configuration = configuration;

        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public Task<APIResult<LoginDTO>> Handle(LoginQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<LoginDTO> result = new APIResult<LoginDTO>();
            result.Code = ResultCode.登录成功;
            result.Message = ResultCode.登录成功.ToString();
            var list = from a in userRep.GetAll()
                       join b in userroleRep.GetAll() on a.UserId equals b.UserId
                       join c in roleRep.GetAll() on b.RoleId equals c.RoleId
                       where a.UserName == request.UserName && a.UserPwd == request.UserPwd
                       select new LoginDTO
                       {
                           UserId = a.UserId,
                           UserName = a.UserName,
                           UserPwd = a.UserPwd,
                           UserNickname = a.UserNickname,
                           RoleId = b.RoleId,
                           RoleName = c.RoleName,
                       };
            var temp = list.FirstOrDefault();
            if (temp == null)
            {
                result.Code = ResultCode.登录失败;
                result.Message = ResultCode.登录失败.ToString() + "用户名和密码不匹配";
                return Task.FromResult(result);
            }
            result.Data = temp;

            return Task.FromResult(result);
        }
        /// <summary>/// 生成 JWT Token（令牌）/// </summary>/// <returns></returns>
        private string CreateTokenString(LoginDTO dto)
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes(_configuration["JWTConfiguration:SecretKey"]);
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            var claims = new[]
            {
                new Claim("UserId",dto?.UserId.ToString()),
                new Claim("UserNickname",dto?.UserNickname??""),
                new Claim("RoleId",dto?.RoleId.ToString())
            };
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: _configuration["JWTConfiguration:Issuer"],
                audience: _configuration["JWTConfiguration:Audience"],
                expires: DateTime.Now.AddDays(1), // 一天后过期
                claims: claims,
                signingCredentials: signingCredentials
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }

    }
}
